package com.geyue.controller;

import com.geyue.common.toolbox.result.Res;
import com.geyue.common.util.StrUtils;
import com.geyue.core.model.User;
import com.geyue.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * Created by Lyon on 2017/4/20.
 */
@Controller
@RequestMapping("/v")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(String mobile, String password, HttpSession session) {
        User user = new User();
        user.setMobile(mobile);
//        user.setPassword(password);

        User u = userService.getOne(user);

        if (u != null) {
            if(!u.getPassword().equals(password)){
                return Res.fail("用户名或密码错误!");
            }
            session.setAttribute("user", u);
            return Res.success("登录成功!");
        }

        return Res.fail("用户名不存在!");
    }

    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public String reg(Model model) {
        return "reg";
    }

    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    @ResponseBody
    public Object reg(@Validated User user, BindingResult binding) {

        if (binding.hasErrors())
            return Res.fail("请求参数错误!");

        return userService.reg(user);

    }

    @RequestMapping(value = "/msg", method = RequestMethod.POST)
    @ResponseBody
    public Object msg(String mobile) {

        if (StrUtils.isEmpty(mobile) || mobile.length() != 11)
            return Res.fail("手机号码格式错误!");

        return userService.msg(mobile);
    }

}
